package com.breakfast.fun.adapter.user;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.breakfast.fun.R;
import com.breakfast.fun.base.BaseListAdapter;
import com.breakfast.fun.data.entity.user.coupon.Coupon;
import com.breakfast.fun.ui.user.coupon.CouponUselessActivity;
import com.breakfast.fun.util.T;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by yukai on 2016/11/10.
 */

public class CouponAdapter extends BaseListAdapter<Coupon.CouponData> {

    private SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    //表示是否展开的使用规则RelativeLayout对应tag的id集合
    private List<Integer> list = new ArrayList<Integer>();
    private double totalPrice = 0;
    private final static int YESCOUPON = 3;

    private static Coupon.CouponData curCoupon;
    private static Boolean isFromUser = false;
    private boolean isNeedShowUseless = true;

    public static Boolean getIsFromUser() {
        return isFromUser;
    }

    public static void setIsFromUser(Boolean isFromUser) {
        CouponAdapter.isFromUser = isFromUser;
    }

    private static TextView checkedTv;

    public Coupon.CouponData getCurCoupon() {
        return curCoupon;
    }

    public void setCurCoupon(Coupon.CouponData curCoupon) {
        this.curCoupon = curCoupon;
    }

    public double getTotalPrice() {
        return totalPrice;
    }

    public void setTotalPrice(double totalPrice) {
        this.totalPrice = totalPrice;
    }

    public CouponAdapter(Context context, List<Coupon.CouponData> list) {
        super(context, list);
    }

    public void setNeedShowUseless(boolean needShowUseless) {
        isNeedShowUseless = needShowUseless;
    }

    @Override
    public View getView(int i, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_coupon, null);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }


        Coupon.CouponData data = getItem(i);
        //订单超时不显示
        if (data.getIsTimeout() != 0) {
            holder.mLlUserItemCoupon.setVisibility(View.GONE);
        } else {
            holder.mLlUserItemCoupon.setVisibility(View.VISIBLE);
            holder.mTvUserCouponName.setText(data.getName());
            holder.mTvUserCouponConditions.setText("满" + data.getConditions() + "使用");
            holder.mTvUserCouponValue.setText(data.getValue() + "");
            if (isNeedShowUseless) {
                holder.mTvUserCouponBettwenTime.setText(data.getBettwenTime());
            } else {
                Date date = new Date();
                try {
                    date = mSimpleDateFormat.parse(data.getCreateTime());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                calendar.add(Calendar.DATE, data.getDeadTime());
                holder.mTvUserCouponBettwenTime.setText(data.getCreateTime() + "~" + mSimpleDateFormat.format(calendar.getTime()));
            }
            holder.mTvUserCouponRule.setText(data.getRule().replace("|", "\n"));

        }

        holder.mRlItemCouponRule.setTag(i);
        holder.mTvUserCouponName.setTag(data.getId());

        //从我的优惠券进入不显示打勾
        if (isFromUser) {
            setDrawable(holder.mTvUserCouponName, null);
        } else {          //已选中优惠券
            if (curCoupon != null) {
                if ((Integer) holder.mTvUserCouponName.getTag() == getCurCoupon().getId()) {
                    setDrawable(holder.mTvUserCouponName, true);
                    checkedTv = holder.mTvUserCouponName;
                } else {
                    setDrawable(holder.mTvUserCouponName, false);
                }
            }
        }


        //避免使用规则显示错乱
        if (list.contains((Integer) holder.mRlItemCouponRule.getTag())) {
            holder.mIvUserCouponRuleArrow.setImageResource(R.drawable.ic_arrow_down_gray);
            holder.mLlItemCouponRule.setVisibility(View.VISIBLE);
        } else {
            holder.mIvUserCouponRuleArrow.setImageResource(R.drawable.ic_arrow_right_gray);
            holder.mLlItemCouponRule.setVisibility(View.GONE);
        }

        if (isNeedShowUseless) {
            if (i == getCount() - 1) {    //可用优惠券最后一项后显示查看不可用优惠券
                holder.mTvUserCouponOut.setVisibility(View.VISIBLE);
            } else {
                holder.mTvUserCouponOut.setVisibility(View.GONE);
            }
        }

        holder.mRlItemCouponRule.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RelativeLayout v = (RelativeLayout) view;
                if (!list.contains(v.getTag())) {
                    list.add((Integer) v.getTag());
                    holder.mLlItemCouponRule.setVisibility(View.VISIBLE);
                    holder.mIvUserCouponRuleArrow.setImageResource(R.drawable.ic_arrow_down_gray);
                } else {
                    list.remove((Integer) v.getTag());
                    holder.mLlItemCouponRule.setVisibility(View.GONE);
                    holder.mIvUserCouponRuleArrow.setImageResource(R.drawable.ic_arrow_right_gray);
                }
            }
        });


        holder.mLlUserCouponSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isFromUser) {
                    return;
                } else {
                    if (getTotalPrice() >= data.getConditions().doubleValue()) {
                        if (holder.mTvUserCouponName != checkedTv && checkedTv != null) {
                            setDrawable(holder.mTvUserCouponName, true);
                            setDrawable(checkedTv, false);
                            checkedTv = holder.mTvUserCouponName;
                        }
                        Intent intent = new Intent();
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("coupon", data);
                        intent.putExtras(bundle);
                        curCoupon = data;
                        ((Activity) mContext).setResult(YESCOUPON, intent);
                        ((Activity) mContext).finish();
                    } else {
                        T.show("还差" + (String.format("%.2f", sub(data.getConditions(), getTotalPrice()))) + "元即可使用优惠券!");
                    }
                }
            }
        });

        holder.mTvUserCouponOut.setOnClickListener(v -> {
            Intent intent = new Intent(mContext, CouponUselessActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            mContext.startActivity(intent);
        });

        return convertView;
    }


    /**
     * 提供精确的减法运算。
     *
     * @param value1 被减数
     * @param value2 减数
     * @return 两个参数的差
     * //
     */

    public double sub(Number value1, Number value2) {
        BigDecimal b1 = new BigDecimal(Double.toString(value1.doubleValue()));
        BigDecimal b2 = new BigDecimal(Double.toString(value2.doubleValue()));
        return b1.subtract(b2).doubleValue();
    }

    /**
     * 设置打勾与否的图标
     *
     * @param tv
     * @param checked true 为打勾，false为不打勾
     */
    public void setDrawable(TextView tv, Boolean checked) {
        Drawable drawable = null;
        if (checked != null) {
            if (checked) {
                drawable = mContext.getResources().getDrawable(R.drawable.ic_pay_checked);
            } else {
                drawable = mContext.getResources().getDrawable(R.drawable.ic_pay_unchecked);
            }
            /// 这一步必须要做,否则不会显示.

            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());

            tv.setCompoundDrawables(null, null, drawable, null);
        } else {
            tv.setCompoundDrawables(null, null, null, null);
        }

    }


    static class ViewHolder {
        @Bind(R.id.tv_user_coupon_value)
        TextView mTvUserCouponValue;
        @Bind(R.id.tv_user_coupon_conditions)
        TextView mTvUserCouponConditions;
        @Bind(R.id.tv_user_coupon_name)
        TextView mTvUserCouponName;
        @Bind(R.id.tv_user_coupon_bettwenTime)
        TextView mTvUserCouponBettwenTime;
        @Bind(R.id.ll_user_coupon_select)
        LinearLayout mLlUserCouponSelect;
        @Bind(R.id.iv_user_coupon_rule_arrow)
        ImageView mIvUserCouponRuleArrow;
        @Bind(R.id.rl_item_coupon_rule)
        RelativeLayout mRlItemCouponRule;
        @Bind(R.id.ll_user_item_coupon)
        LinearLayout mLlUserItemCoupon;
        @Bind(R.id.tv_user_coupon_rule)
        TextView mTvUserCouponRule;
        @Bind(R.id.rl_user_item_coupon)
        RelativeLayout mRlUserItemCoupon;
        @Bind(R.id.tv_sign)
        TextView mTvSign;
        @Bind(R.id.tv_user_item_coupon_out)
        TextView mTvUserCouponOut;
        @Bind(R.id.ll_item_coupon_rule)
        LinearLayout mLlItemCouponRule;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
